using AutoMapper;
using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.DeviceClassificationDictionaryCommand;
using Medical.Api.Read.Dto.BasicManagement.DeviceClassificationDictionaryDto;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.BasicManagement.DeviceClassificationDictionaryHandler
{
    /// <summary>
    /// 获取器械分类树状结构处理器
    /// </summary>
    public class GetApparatusTypeTreeHandler : IRequestHandler<GetApparatusTypeTreeCommand, ApiResult<List<ApparatusTypeTreeDto>>>
    {
        private readonly IBaseRepository<ApparatusType> _apparatusTypeRepository;
        private readonly ILogger<GetApparatusTypeTreeHandler> _logger;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="apparatusTypeRepository">器械分类仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="mapper">对象映射器</param>
        public GetApparatusTypeTreeHandler(
            IBaseRepository<ApparatusType> apparatusTypeRepository,
            ILogger<GetApparatusTypeTreeHandler> logger,
            IMapper mapper)
        {
            _apparatusTypeRepository = apparatusTypeRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取器械分类树状结构请求
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>器械分类树状结构</returns>
        public Task<ApiResult<List<ApparatusTypeTreeDto>>> Handle(GetApparatusTypeTreeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取器械分类树状结构");

                // 查询未删除的器械分类
                var query = _apparatusTypeRepository.GetAll().Where(x => !x.IsDeleted);

                // 根据请求筛选状态
                if (request.Status.HasValue)
                {
                    query = query.Where(x => x.Status == request.Status.Value);
                }

                // 获取所有符合条件的分类
                var allApparatusTypes = query.ToList();

                // 映射到DTO
                var allDtos = _mapper.Map<List<ApparatusTypeTreeDto>>(allApparatusTypes);

                // 构建树状结构
                var treeResult = BuildTree(allDtos);

                _logger.LogInformation("成功获取器械分类树状结构");

                return Task.FromResult(new ApiResult<List<ApparatusTypeTreeDto>>
                {
                    Code = ApiEnums.Success,
                    Msg = "获取成功",
                    Data = treeResult
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取器械分类树状结构时发生异常");
                return Task.FromResult(new ApiResult<List<ApparatusTypeTreeDto>>
                {
                    Code = ApiEnums.Fail,
                    Msg = "获取失败：系统内部错误",
                    Data = new List<ApparatusTypeTreeDto>()
                });
            }
        }

        /// <summary>
        /// 构建树状结构
        /// </summary>
        /// <param name="allTypes">所有器械分类列表</param>
        /// <returns>树状结构的器械分类列表</returns>
        private List<ApparatusTypeTreeDto> BuildTree(List<ApparatusTypeTreeDto> allTypes)
        {
            // 结果集（根节点列表）
            var rootNodes = new List<ApparatusTypeTreeDto>();

            // 使用字典以提高查找效率
            var typeDict = allTypes.ToDictionary(x => x.Id);

            foreach (var type in allTypes)
            {
                // 如果没有父节点，则为根节点
                if (!type.ParentId.HasValue || !typeDict.ContainsKey(type.ParentId.Value))
                {
                    rootNodes.Add(type);
                }
                else
                {
                    // 将当前节点添加到父节点的子节点列表中
                    var parent = typeDict[type.ParentId.Value];
                    parent.Children.Add(type);
                }
            }

            return rootNodes;
        }
    }
}